package com.appspot.yusupova;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.appspot.yusupova.verses.VerseMap;

@SuppressWarnings("serial")
public final class SaveVerseIndexServlet extends AdminHttpServlet {
    
    private static final String REQ_PARAM_WORD          = "word";
    private static final String REQ_PARAM_VERSE_INDEXES = "verse_indexes";
    
    public void doAuthorizedPost(HttpServletRequest req, HttpServletResponse resp, PrintWriter writer) throws IOException {
        String word = req.getParameter(REQ_PARAM_WORD);
        if (word != null) {
            String idsString = req.getParameter(REQ_PARAM_VERSE_INDEXES);
            if (idsString != null) {
                StringTokenizer parsedIds = new StringTokenizer(idsString, ",");
                List<Long> verseIds = new ArrayList<Long>();
                while (parsedIds.hasMoreElements()) {
                    Long verseId = Long.parseLong(parsedIds.nextToken());
                    verseIds.add(verseId);
                }
                VerseMap.putIndex(word, verseIds);
                writer.println("Verse index has been saved. I hope :)");
            } else {
                writer.println("Missed parameter:" + REQ_PARAM_VERSE_INDEXES);
            }
        } else {
            writer.println("Missed parameter:" + REQ_PARAM_WORD);
        }
    }

}
